package io.plus.client;

import drds.common.Clock;
import io.plus.utils.thread.lock_capable_task.AbstractTask;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executor;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

@Slf4j
public class ReConnectRunnable extends AbstractTask {
    ClientAsynchronousSocketChannelContext clientChannelContext = null;
    Client client = null;


    public ReConnectRunnable(ClientAsynchronousSocketChannelContext clientChannelContext, Client client, Executor executor) {
        super(executor);
        this.clientChannelContext = clientChannelContext;
        this.client = client;
    }

    @Override
    public boolean isNeededExecute() {
        return false;
    }

    @Override
    public void runTask() {
        clientChannelContext.getReConnectCount().incrementAndGet();
        ReentrantReadWriteLock closeLock = clientChannelContext.closeLock;
        WriteLock writeLock = closeLock.writeLock();
        writeLock.lock();
        try {
            //已经连上了，不需要再重连了
            if (!clientChannelContext.isClosed) {
                return;
            }
            long start = Clock.currentTimeMillis;
            client.reconnect(clientChannelContext, 2);
            long end = Clock.currentTimeMillis;
            long interval = end - start;
            log.error("{}, 第{}次重连,重连耗时:{} ms", clientChannelContext, clientChannelContext.getReConnectCount(), interval);
        } catch (java.lang.Throwable e) {
            log.error(e.toString(), e);
        } finally {
            writeLock.unlock();
        }

    }
}
